package org.sakai.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.sakai.entity.*;
import org.sakai.entity.Image;
import org.sakai.entity.vo.ConsultVO;
import org.sakai.service.ConsultService;
import org.sakai.service.MinioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/consult")
public class ConsultController {
    @Autowired
    ConsultService consultService;
    @Autowired
    MinioService minioService;
    @GetMapping("/dep/all")
    public ResponseEntity<List<Departments>> getAllDepartments() {
        Result<List<Departments>> result = consultService.getDepartmentList();
        return ApiResponseEntity.getResponseEntity(result);
    }

    @GetMapping("/price/{doctorId}")
    public ResponseEntity<Double> getPriceByDoctorId(@PathVariable String doctorId) {
        Result<Double> result = consultService.getPriceByDoctorId(doctorId);
        return ApiResponseEntity.getResponseEntity(result);
    }

    @PostMapping(path = "/upload/images/{consultId}")
    public ResponseEntity<Void> uploadImage(@RequestParam("file") MultipartFile file,
                                            @PathVariable String consultId) {
        // 验证文件
        if (file.isEmpty()) {
            return ApiResponseEntity.error(ErrorCode.FILE_NOT_FOUND);
        }

        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return ApiResponseEntity.error(ErrorCode.FILE_TYPE_ERROR);
        }

        // 调用服务层处理上传
        Result<Image> result = minioService.upload("big-data-health", consultId + "/images" , file);
        return ApiResponseEntity.getResponseEntity(result);
    }


    @PostMapping("/order/add")
    public ResponseEntity<String> addOrder(@RequestBody Consult consult) {
        Result<String> result = consultService.addConsult(consult);
        return ApiResponseEntity.getResponseEntity(result);
    }

    @GetMapping("/order/detail/{consultId}")
    public ResponseEntity<ConsultVO> getConsultDetail(@PathVariable String consultId) {
        Result<ConsultVO> consultDetail = consultService.getConsultDetail(consultId);
        return ApiResponseEntity.getResponseEntity(consultDetail);
    }

    @RequestMapping("/images/{filename}")
    public void downloadImage(@RequestParam String orderId, @PathVariable String filename, HttpServletResponse response) {
        try {
            // 获取文件流并写入响应
            InputStream fileStream = minioService.getFileAsStream(orderId, filename);
            if (fileStream != null) {
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);
                int bufferSize = Math.min(8192, (int) Math.max(fileStream.available(), 1024));
                byte[] buffer = new byte[bufferSize];
                int bytesRead;
                while ((bytesRead = fileStream.read(buffer)) != -1) {
                    response.getOutputStream().write(buffer, 0, bytesRead);
                }
                fileStream.close();
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
            }
        } catch (Exception e) {
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred");
            } catch (IOException ioEx) {
                ioEx.printStackTrace();
            }
            e.printStackTrace();
        }
    }
}
